package io.xccit.realm;

import io.xccit.entity.User;
import io.xccit.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *@author CH_ywx
 *@Date 2023-06-01
 *@Description 自定义加密认证登陆
 */
@Component
public class CustomLoginRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;
    /**
     * 自定义授权方法
     * @param principalCollection 认证信息
     * @return 校验逻辑对象
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入自定义授权方法doGetAuthorizationInfo()...");
        /*模拟用户角色认证*/
        /*//创建对象,封装当前用户及角色信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加角色(本应该是去数据库查)
        info.addRole("admin");*/
        /*模拟数据库真实环境用户角色认证*/
        //调用service获取用户角色信息
        List<String> userRoleByName = userService.getUserRoleByName(principalCollection.getPrimaryPrincipal().toString());
        //调用service获取用户角色权限信息
        List<String> userRolePermissionsByRoleName = userService.getUserRolePermissionsByRoleName(userRoleByName);
        //创建对象封装用户角色信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将用户角色信息放入对象当中
        info.addRoles(userRoleByName);
        //将用户角色权限信息放入对象当中
        info.addStringPermissions(userRolePermissionsByRoleName);
        return info;
    }

    /**
     * 自定义登录认证方法
     * @param authenticationToken 令牌信息
     * @return 校验逻辑对象
     * @throws AuthenticationException 失败异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取身份信息
        String username = authenticationToken.getPrincipal().toString();
        //调用方法从数据库查
        User user = userService.login(username);
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                authenticationToken.getPrincipal(),//用户名
                user.getPassword(),//数据库查出的密码
                ByteSource.Util.bytes("2001"),//盐信息
                authenticationToken.getPrincipal().toString()//当前的realm
        );
        if (user != null){
            return info;
        }
        return null;
    }
}
